﻿using System;
using System.Web.UI;

namespace PD.Web.DynamicData.FieldTemplates
{
    /// <summary>
    /// Represents the foreign key field template control.
    /// </summary>
    public partial class ForeignKeyField : System.Web.DynamicData.FieldTemplateUserControl
    {
        /// <summary>
        /// A value indicating whether a navigation to the children element is allowed.
        /// </summary>
        private bool allowNavigation = true;

        /// <summary>
        /// Gets or sets the navigate URL.
        /// </summary>
        /// <value>
        /// The navigate URL.
        /// </value>
        public string NavigateUrl
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether a navigation to the children element is allowed.
        /// </summary>
        /// <value>
        ///   <c>true</c> if a navigation to the children element is allowed; otherwise, <c>false</c>.
        /// </value>
        public bool AllowNavigation
        {
            get
            {
                return this.allowNavigation;
            }

            set
            {
                this.allowNavigation = value;
            }
        }

        /// <summary>
        /// Gets the data control that handles the data field in a field template.
        /// </summary>
        /// <returns>A data control that handles the data field in a field template.</returns>
        public override Control DataControl
        {
            get
            {
                return this.HyperLink1;
            }
        }

        /// <summary>
        /// Gets the display string.
        /// </summary>
        /// <returns>
        /// The display string.
        /// </returns>
        protected string GetDisplayString()
        {
            object value = this.FieldValue;

            if (value == null)
            {
                return this.FormatFieldValue(this.ForeignKeyColumn.GetForeignKeyString(this.Row));
            }
            else
            {
                return this.FormatFieldValue(this.ForeignKeyColumn.ParentTable.GetDisplayString(value));
            }
        }

        /// <summary>
        /// Gets the navigate URL.
        /// </summary>
        /// <returns>
        /// The navigate URL.
        /// </returns>
        protected string GetNavigateUrl()
        {
            if (!this.AllowNavigation)
            {
                return null;
            }

            if (string.IsNullOrEmpty(this.NavigateUrl))
            {
                return this.ForeignKeyPath;
            }
            else
            {
                return this.BuildForeignKeyPath(this.NavigateUrl);
            }
        }
    }
}
